﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace Charts.Converters
{
	/// <summary>
	/// Sources is here:
	/// http://habrahabr.ru/post/140876/ &
	/// http://www.codeproject.com/Articles/35416/Use-of-MarkupExtension-with-Converters-in-WPF
	/// </summary>
	[MarkupExtensionReturnType(typeof(IValueConverter))]
	public abstract class ConverterBase<T> : MarkupExtension, IValueConverter
		where T : class, new()
	{
		#region IValueConverter members
		/// <summary>
		/// Must be implemented in inheritor
		/// </summary>
		public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture);
		
		/// <summary>
		/// return DependencyProperty.UnsetValue. Override if needed
		/// </summary>
		public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			return DependencyProperty.UnsetValue;
		}
		#endregion
		
		#region MarkupExtension members
		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			if (converter == null)
				converter = new T();
			
			return converter;
		}
		
		private static T converter = null;
		#endregion
	}
}
